﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuaInterface;
using UnityEngine;
using LuaFramework;

namespace GMBase.Lua
{
    /// <summary>
    /// lua动态加载。
    /// </summary>
    class LuaLoaderForAssetBundle : LuaFileUtils
    {
        public LuaLoaderForAssetBundle()
        {
            LuaFileUtils.Instance = this;
        }

        /// <summary>
        /// 当LuaVM加载Lua文件的时候，这里就会被调用，
        /// 用户可以自定义加载行为，只要返回byte[]即可。
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public override byte[] ReadFile(string fileName)
        {
            if (!fileName.Contains("require"))
            {
                return LuaLoaderForResource.ReadFileFromResource(fileName);
            }

            Debug.LogError("data path = " + Util.DataPath);
            AssetBundle ab = AssetBundle.LoadFromFile(Util.DataPath + @"/ABs/lua");
            var pos = fileName.LastIndexOf("/");
            if (pos > 0)
            {
                fileName = fileName.Substring(pos + 1).ToLower() + ".lua.bytes";// unity5 assetbund'name must lower
            }
            var lua = ab.LoadAsset<TextAsset>(fileName);
            return lua.bytes;
        }
    }
}
